const db = wx.cloud.database()
let type
let detail
var isConfirm
const app=getApp()
Page({
  data: {
    //isThr
    major:['邻里互助','儿童助学','农业生产','照顾老人'],
    question:['敬老爱老','科学普及','文明乡村','信息普及','政策普及'],
    culture:['核酸检测','知识普及','疫情教育'],
    residemajor:'',
    residequestion:'',
    resideculture:'',
    //isThr
    idcountry: ['中国', '中国香港', '中国澳门', '中国台湾'],
    idType: ['内地居民身份证', '香港居民身份证', '澳门居民身份证', '台湾居民身份证'],
    index: "",
    isOne: true, isTwo: false, isThr: false,
    code: "", phone: "", Name: "", ID: "", region: "",oriTypeValue:"",
    oriType: [['学校', '政府', '企业'], ['中小学', '大学']],
    errMe: [{type: "teamName",name: "团体名称"},
           {type: "teamRegion",name: "所在地区",}, 
          {type: "teamType",name: "组织类型",},
          {type: "IDType",name: "正确的证件类型",},
          {type: "IDNum",name: "正确的证件号码",},
          {type: "name",name: "正确的姓名",},
          {type: "phone",name: "正确的手机号",}
  ],
    errMes: {
      teamNameErrMes: "",
      teamRegionErrMes:"",
      teamTypeErrMes:"",
      IDNumErrMes:"",
      nameErrMes:"",
      phoneErrMes:""
    },
    teamInfo: {
      teamName: "",
      teamID: "",
      teamRegion: "",
      teamDetailRegion: "",
      teamIntro: "",
      teamImg:"",
      signInTime:""
    },
    managerInfo:{
      name:"",
      IDNum:"",
      IDType:"",
      phone:"",
    },
    isConfirm:false,
    imageList:[],
    imgUrl:[]
  },
  afterRead(e) {
    console.log(e)
    let temp = {
      url: e.detail.file.url,
      deletable: true,
    }
    let tempImage = []
    tempImage[0] = temp
    this.setData({
      imageList: tempImage
    })
  },
  deleteImage(e) {
    console.log(e)
    let tempImage = []
    this.setData({
      imageList: tempImage
    })

  },
  getInput(e) {
    type = e.currentTarget.dataset.type
    detail = e.detail
    this.checkTeamInfo(type, detail)
    if(this.data.isOne==true){
    this.setData({
      ['teamInfo.' + type]: detail
    })
  }
  if(this.data.isTwo==true)
  {
    this.setData({
      ['managerInfo.' + type]: detail
    })
    this.checkName()
    this.identityCodeValid()
    this.checkphone()
  }
  },
  checkTeamInfo(type, detail) {
    
    if (detail == "") {
      for (var i = 0; i < this.data.errMe.length; i++) {
        if (this.data.errMe[i].type == type)
          var Name = this.data.errMe[i].name
      }
      this.setData({
        ['errMes.' + type + 'ErrMes']: "请输入" + Name
      })
      return false;
    }
    else {
      this.setData({
        ['errMes.' + type + 'ErrMes']: ""
      })
      return true;
    }
  },
  changeOriType(e) {
    console.log(e.detail.value)
    if (e.detail.column == 0) {
      if (e.detail.value == 1)
        this.setData({
          oriType: [['学校', '政府', '企业'], ['市政府', '区政府', '乡政府', '村委会']]
        })
      else if (e.detail.value == 2)
        this.setData({
          oriType: [['学校', '政府', '企业'], ['国有企业', '非国有企业']]
        })
      else if (e.detail.value == 0)
        this.setData({
          oriType: [['学校', '政府', '企业'], ['中小学', '大学']]
        })
    }

  },
  oriTypeChange(e){
   
    console.log(e)
    this.setData({
      oriTypeValue:this.data.oriType[1][e.detail.value[1]]
    })
    this.checkTeamInfo('teamType',this.data.oriTypeValue)
  },
  //检测姓名（是否是汉字）
  checkName() {
    let name=this.data.managerInfo.name
    console.log("checkName",name)
    let reg = /^[\u2E80-\u9FFF]+$/;
    if (!reg.test(name)) {
      console.log("执行")
      this.setData({ ['errMes.nameErrMes']: "姓名格式错误" })
      return false
    }
    else {
      this.setData({ nameErrMes: "" })
      return true
    }
  },
  //检测身份证号的合法性
  identityCodeValid() {
    var city = {
      11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 "
    };
    var idCardReg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/g;
    var code = this.data.managerInfo.IDNum
    if (!code || !idCardReg.test(code)) {
      this.setData({ ['errMes.IDNumErrMes']: "身份证号码错误，请重新输入" })
      return false
    } else if (!city[code.substr(0, 2)]) {
      this.setData({ ['errMes.IDNumErrMes']: "身份证号码错误，请重新输入" })
      return  false
    } else {
      //18位身份证需要验证最后一位校验位
      if (code.length == 18) {
        code = code.split('');
        //∑(ai×Wi)(mod 11)
        //加权因子
        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        //校验位
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        var sum = 0;
        var ai = 0;
        var wi = 0;
        for (var i = 0; i < 17; i++) {
          ai = code[i];
          wi = factor[i];
          sum += ai * wi;
        }
        var last = parity[sum % 11];
        if (parity[sum % 11] != code[17]) {
          this.setData({ ['errMes.IDNumErrMes']: "身份证号码错误，请重新输入" })
          return false
        }
      }
    }
    return true
  },
  //进入下一步
  enterNext() {
    let teamName = this.data.teamInfo.teamName
let name=this.data.managerInfo.name
let phone=this.data.managerInfo.phone
let IDNum=this.data.managerInfo.IDNum
    if (this.data.isOne) {
      this.checkTeamInfo('teamName', teamName)
      this.checkTeamInfo('teamRegion',this.data.region)
      this.checkTeamInfo('teamType',this.data.oriTypeValue)
      if (this.checkTeamInfo('teamName', teamName)&&this.checkTeamInfo('teamRegion',this.data.region)&&
      this.checkTeamInfo('teamType',this.data.oriTypeValue)) {
        this.setData({
          isOne: false,
          isTwo: true
        })
      }
    }
    if(this.data.isTwo)
    {
      this.checkTeamInfo('name', name)
      this.checkTeamInfo('phone', phone)
      this.checkTeamInfo('IDNum', IDNum)
      this.checkName()
      console.log(this.checkName())
      this.identityCodeValid()
      console.log( this.identityCodeValid())
      this.checkphone()
      console.log( this.checkphone())
      if( this.checkTeamInfo('name', name)&& this.checkTeamInfo('phone', phone)&&this.checkTeamInfo('IDNum', IDNum)&&this.checkName()&&this.identityCodeValid()&&this.checkphone())
      this.setData({
        isTwo: false,
        isThr:true
      })
    }
  },
  //返回上一步
  return() {
    if (this.data.isTwo)
      this.setData({
        isOne: true,
        isTwo: false
      })
    if (this.data.isThr)
      this.setData({
        isTwo: true,
        isThr: false
      })
  },
  //检查手机号格式
  checkphone() {
    var phoneReg = /^1[3456789]\d{9}$/
    if (!phoneReg.test(this.data.managerInfo.phone)) {
      this.setData({ ['errMes.phoneErrMes']: "手机号码格式错误,请重新输入" })
      return false
    }
    else {
      this.setData({ ['errMes.phoneErrMes']: "" })
      return true
    }
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
 
  idGet() {
    let ID = app.getID(4,2)
    console.log("Id", ID)
    this.setData({
      ID: ID
    })
    this.data.teamInfo.teamID=ID
    this.setData({
      teamInfo:this.data.teamInfo
    })
  },
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
    this.checkTeamInfo('teamRegion',this.data.region)
  },
  //专业对口
  majorChoose(e){
      console.log('majorChoose',this.data.major[parseInt(e.detail.value)] );
      this.setData({residemajor:this.data.major[parseInt(e.detail.value)]})
  },
  //问题解决
  questionChoose(e){
      console.log('questionChoose',this.data.question[parseInt(e.detail.value)] );
      this.setData({residequestion:this.data.question[parseInt(e.detail.value)]});
  },
  //文化建设
  cultureChoose(e){
      console.log('cultureChoose',this.data.culture[parseInt(e.detail.value)] );
      this.setData({resideculture:this.data.culture[parseInt(e.detail.value)]});
  },
  async signIn() {
    if(!isConfirm)
    {
      wx.showToast({
        title: '请先勾选用户隐私协议',
        icon:"none"
      })
    }
    else{
      console.log(this.data.imageList)
      await wx.cloud.uploadFile({
       cloudPath: app.globalData.openid+Math.random()+ ".png",
       filePath: this.data.imageList[0].url, // 文件路径
     }).then(res => {
       console.log("文件", res.fileID)
       this.data.imgUrl.push({
         Url: res.fileID
       })
       console.log("this.data.imgUrl",this.data.imgUrl)
     })
     this.data.teamInfo.teamImg=this.data.imgUrl[0].Url
     this.data.teamInfo.signInTime=app.getTime(1)
     this.data.teamInfo.teamRegion=this.data.region
     db.collection('all_team')
       .add({
         data: {
           teamInfo:this.data.teamInfo,
           managerInfo: this.data.managerInfo,
           comment: [],
           memberNotAdmit:[],
           memberAdmit:[],
           mySession_ids:[]
         }
       })
       .then(res => {
         console.log(res)
         wx.navigateTo({
           url: '../team/team',
         })
       })
    }
   
    
  },
  tapToConfirm(){
    this.setData({
      isConfirm:!isConfirm
    })
    isConfirm=!isConfirm
  },
})